﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SuperMap.Data;
using SuperMap.UI;
using SuperMap.Mapping;
using SuperMap.Data.Conversion;
using System.IO;

namespace MDF
{
    class DataManage
    {
        //初始引用变量
        private Workspace m_workspace;
        private Datasource m_datasource;
        private DatasourceConnectionInfo m_datasourceConnectionInfo;

        //配置文件名
        //private string m_xmlName = "MDFSYSTEAM";

        //private IO_xml dm_Xml;

        /// <summary>
        /// 初始化构造函数
        /// </summary>
        public DataManage(){ }
        /// <summary>
        /// 初始化构造函数
        /// </summary>
        /// <param name="workspace">传递工作空间</param>
        public DataManage(Workspace workspace)
        {
            try
            {
                //获取变量
                m_workspace = workspace;
                CreateDatasourceDefault();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 创建默认数据源
        /// </summary>
        private void CreateDatasourceDefault()
        {
            try
            {
                m_datasourceConnectionInfo = new DatasourceConnectionInfo();

                // 设置数据源位置为可启动程序所在的Source中，类型为UDB
                m_datasourceConnectionInfo.Alias = "默认数据源";
                m_datasourceConnectionInfo.EngineType = EngineType.UDB;
                m_datasourceConnectionInfo.Server = Application.StartupPath+"\\Source\\Default";
                //判断数据源是否存在
                if (File.Exists(Application.StartupPath + "\\Source\\Default.udb"))
                {
                    m_datasource = m_workspace.Datasources.Open(m_datasourceConnectionInfo);
                    //清空默认数据源
                    m_datasource.Datasets.DeleteAll();
                }
                else
                {
                    m_datasource = m_workspace.Datasources.Create(m_datasourceConnectionInfo);
                }
                
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 切换操作的数据源
        /// </summary>
        /// <param name="sourceAlias"></param>
        public void ChangeDatasource(string sourceAlias)
        {
            try
            {
                m_datasource = m_workspace.Datasources[sourceAlias];
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="fileName">文件完整路径</param>
        public void OpenFile(string fileName)
        {
            try
            {
                string result;
                ImportResult importResult;
                string im_Name = System.IO.Path.GetExtension(fileName);//判断文件类型
                //优化GeoJson文件读取
                if (im_Name.Equals(".json")) { im_Name = ".geojson"; }
                //导入对应文件
                switch (im_Name)
                {
                    case ".shp":
                        //构建shp导入对象
                        ImportSettingSHP importSettingSHP = new ImportSettingSHP(fileName,m_datasource);//导入的完整路径，导入到**数据源
                        //构建数据导入类,添加导入对象集合
                        DataImport dataImportSHP = new DataImport();
                        ImportSettings importSettingsSHP = dataImportSHP.ImportSettings;
                        importSettingsSHP.Add(importSettingSHP);
                        //导入数据，并获取结果
                        importResult = dataImportSHP.Run();
                        result = "成功个数为：" + importResult.SucceedSettings.Length.ToString();
                        MessageBox.Show(result,"提示：");
                        dataImportSHP.Dispose();//释放占用资源
                        break;
                    case ".geojson":
                        //构建geojson导入对象
                        ImportSettingGeoJson importSettingGEOJSON = new ImportSettingGeoJson(fileName, m_datasource);//导入的完整路径，导入到**数据源
                        importSettingGEOJSON.SourceFileCharset = Charset.UTF8;//设置导入字符集格式
                        //构建数据导入类,添加导入对象集合
                        DataImport dataImportGEOJSON = new DataImport();
                        ImportSettings importSettingsGEOJSON = dataImportGEOJSON.ImportSettings;
                        importSettingsGEOJSON.Add(importSettingGEOJSON);
                        //导入数据，并获取结果
                        importResult = dataImportGEOJSON.Run();
                        result = "成功个数为：" + importResult.SucceedSettings.Length.ToString();
                        MessageBox.Show(result, "提示：");
                        dataImportGEOJSON.Dispose();//释放占用资源
                        break;
                    case ".dwg":
                        //构建geojson导入对象
                        ImportSettingDWG importSettingDWG = new ImportSettingDWG(fileName, m_datasource);//导入的完整路径，导入到**数据源
                        importSettingDWG.SourceFileCharset = Charset.UTF8;//设置导入字符集格式
                        //构建数据导入类,添加导入对象集合
                        DataImport dataImportDWG = new DataImport();
                        ImportSettings importSettingsDWG = dataImportDWG.ImportSettings;
                        importSettingsDWG.Add(importSettingDWG);
                        //导入数据，并获取结果
                        importResult = dataImportDWG.Run();
                        result = "成功个数为：" + importResult.SucceedSettings.Length.ToString();
                        MessageBox.Show(result, "提示：");
                        dataImportDWG.Dispose();//释放占用资源
                        break;
                    default:
                        MessageBox.Show("未知文件", "提示：");
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 打开数据源
        /// </summary>
        /// <param name="fileName">文件完整路径</param>
        public void OpenDatasource(string fileName)
        {
            try
            {
                string im_Name = System.IO.Path.GetExtension(fileName);//判断文件类型
                switch (im_Name)
                {
                    case ".udb":
                        //构建数据库连接信息对象
                        m_datasourceConnectionInfo = new DatasourceConnectionInfo();
                        m_datasourceConnectionInfo.EngineType = EngineType.UDB;
                        m_datasourceConnectionInfo.Alias = Path.GetFileNameWithoutExtension(fileName);
                        m_datasourceConnectionInfo.Server = fileName;

                        m_datasource = m_workspace.Datasources.Open(m_datasourceConnectionInfo);
                        if (m_datasource != null)
                        {
                            MessageBox.Show("打开成功！", "提示：");
                        }
                        break;
                    default:
                        MessageBox.Show("未知文件", "提示：");
                        break;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 保存数据源
        /// </summary>
        /// <param name="sourceName">数据源名称</param>
        /// <param name="fileName">文件完整路径</param>
        public void SaveDataSource(string sourceName,string fileName)
        {
            try
            {
                string nd_Name = System.IO.Path.GetExtension(fileName);//判断文件类型
                switch (nd_Name)
                {
                    case ".udb":
                        //1.新建一个udb数据源
                        string dataSourceName = fileName.Replace(nd_Name, "");//获取数据源保存路径，不带拓展名
                        m_datasourceConnectionInfo = new DatasourceConnectionInfo();
                        m_datasourceConnectionInfo.EngineType = EngineType.UDB;
                        m_datasourceConnectionInfo.Server = dataSourceName;
                        m_datasourceConnectionInfo.Alias = Path.GetFileNameWithoutExtension(fileName);
                        Datasource s_datasource = m_workspace.Datasources.Create(m_datasourceConnectionInfo);
                        //2.复制旧数据源的数据到新数据源中（数据源创建及默认打开）
                        foreach (Dataset dataset in m_workspace.Datasources[sourceName].Datasets)//遍历旧数据源的数据，并复制
                        {
                            string datasetName = s_datasource.Datasets.GetAvailableDatasetName(dataset.Name);
                            s_datasource.CopyDataset(dataset, datasetName, EncodeType.None);
                        }
                        if (s_datasource.Datasets.Count == m_workspace.Datasources[sourceName].Datasets.Count)
                        {
                            MessageBox.Show("保存成功！", "提示：");
                        }
                        else
                        {
                            int count = m_workspace.Datasources[sourceName].Datasets.Count - s_datasource.Datasets.Count;
                            MessageBox.Show("保存失败数据："+count.ToString()+"个！","警告：");
                        }
                        break;
                    default:
                        MessageBox.Show("未知文件", "提示：");
                        break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 新建数据源
        /// </summary>
        /// <param name="fileName"></param>
        public void CreateDataSource(string fileName)
        {
            try
            {
                string nd_Name = System.IO.Path.GetExtension(fileName);//判断文件类型
                switch (nd_Name)
                {
                    case ".udb":
                        m_datasourceConnectionInfo = new DatasourceConnectionInfo();

                        //新建数据源类型为UDB
                        m_datasourceConnectionInfo.Alias = Path.GetFileNameWithoutExtension(fileName);
                        m_datasourceConnectionInfo.EngineType = EngineType.UDB;
                        m_datasourceConnectionInfo.Server = fileName;

                        m_datasource = m_workspace.Datasources.Create(m_datasourceConnectionInfo);
                        
                        break;
                    default:
                        MessageBox.Show("未知文件", "提示：");
                        break;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 另存文件
        /// </summary>
        /// <param name="fileName">文件完整路径</param>
        /// <param name="selectNode">用户选中的工作空空间树节点</param>
        public void SaveOtherFile(string fileName, WorkspaceTreeNodeBase selectNode)
        {
            try
            {
                string result;
                ExportResult exportResult;
                if (!m_datasource.Datasets.IsAvailableDatasetName(selectNode.Text))//判断是否选中合法数据节点
                {
                    string ex_Name = System.IO.Path.GetExtension(fileName);//判断文件类型
                    switch (ex_Name)
                    {
                        case ".shp":
                            //构建导出对象
                            ExportSetting exportSettingSHP = new ExportSetting(m_datasource.Datasets[selectNode.Text], fileName, FileType.SHP);//需要导出的矢量数据集，导出的完整路径，导出类型
                            //构建数据导出类,添加导出对象集合
                            DataExport dataExportSHP = new DataExport();
                            dataExportSHP.ExportSettings.Add(exportSettingSHP);
                            //导出数据，并获取结果
                            exportResult = dataExportSHP.Run();
                            result = "成功个数为：" + exportResult.SucceedSettings.Length.ToString();
                            MessageBox.Show(result, "提示：");
                            dataExportSHP.Dispose();//释放导出类
                            break;
                        case ".json":
                            //构建geojsond导出对象
                            ExportSettingGeoJson exportSettingGEOJSON = new ExportSettingGeoJson(m_datasource.Datasets[selectNode.Text], fileName);//需要导出的矢量数据集，导出的完整路径，导出类型
                            exportSettingGEOJSON.TargetFileCharset = Charset.UTF8;//设置导出字符集格式
                            //构建数据导出类,添加导出对象集合
                            DataExport dataExportGEOJSON = new DataExport();
                            dataExportGEOJSON.ExportSettings.Add(exportSettingGEOJSON);
                            //导出数据，并获取结果
                            exportResult = dataExportGEOJSON.Run();
                            result = "成功个数为：" + exportResult.SucceedSettings.Length.ToString();
                            MessageBox.Show(result, "提示：");
                            dataExportGEOJSON.Dispose();//释放导出类
                            break;
                        default:
                            MessageBox.Show("未知文件", "提示：");
                            break;
                    }


                }
                else
                {
                    MessageBox.Show("选中的数据集不合法！","错误提示：");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 关闭数据源
        /// </summary>
        /// <param name="maps">地图窗口所展示的地图集合</param>
        /// <param name="layersS">图层空间所展示图层集合</param>
        /// <param name="datasource">所选择的数据源</param>
        public string[] CloseSource(Map[] maps, Layers[] layersS, Datasource datasource)
        {
            try
            {
                string Tishi = "确定关闭" + datasource.Alias + "数据源？";
                if (MessageBox.Show(Tishi, "提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    //获取有关联的数据集名
                    List<string> setsName = new List<string>();
                    for (int i = 0; i < maps.Length; i++)
                    {
                        //获取有关联的数据集名
                        foreach (Layer layer in layersS[i])
                        {
                            if (layer.Name.Contains(datasource.Alias))
                            {
                                setsName.Add(layer.Name);
                            }
                        }
                        //移除有关联的图层
                        foreach (string setName in setsName)
                        {
                            layersS[i].Remove(setName);
                        }
                        //刷新地图窗口
                        maps[i].Refresh();
                    }
                    //关闭数据源
                    datasource.Close();
                    return setsName.ToArray();
                }
                else
                {
                    return new string[] { };
                }

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 删除数据集
        /// </summary>
        /// <param name="maps">地图窗口所展示的地图集合</param>
        /// <param name="layersS">图层空间所展示图层集合</param>
        /// <param name="datasource">数据集所在的数据源</param>
        /// <param name="selectNode">用户选中的工作空间树节点</param>
        public void DeleteSet(Map[] maps, Layers[] layersS, Datasource datasource, WorkspaceTreeNodeBase selectNode)
        {
            try
            {
                string Tishi = "删除的数据集将无法恢复!\r\n你确定要删除" + selectNode.Text + "吗？";
                if (MessageBox.Show(Tishi, "删除提示：", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    for (int i = 0; i < maps.Length; i++)
                    {
                        layersS[i].Remove(selectNode.Text + "@" + datasource.Alias);//移除同名图层
                        if (selectNode.FirstNode != null)//如果子数据集不为空
                        {
                            layersS[i].Remove(selectNode.FirstNode.Text + "@" + datasource.Alias);//移除子图层
                        }
                        maps[i].Refresh();//刷新地图窗口
                    }
                    datasource.Datasets.Delete(selectNode.Text);//删除数据集
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 将数据集加载到地图窗口
        /// </summary>
        /// <param name="map">地图窗口所展示的地图</param>
        /// <param name="layers">图层空间所展示图层</param>
        /// <param name="selectNode">用户选中的工作空间树节点</param>
        public void ToMapSet(Map map, Layers layers, WorkspaceTreeNodeBase selectNode)
        {
            try
            {
                if (selectNode.NodeType == WorkspaceTreeNodeDataType.DatasetVector)//判断数据类型
                {
                    DatasetVector datasetVector = selectNode.GetData() as DatasetVector;//获取数据
                    if (map != null)//判断地图是否存在
                    {
                        if (layers.Count == 0)//判断图层地图是否有数据文件
                        {
                            layers.Add(datasetVector, true);
                            if (datasetVector.ChildDataset != null)//判断是否有子数据集
                            {
                                layers.Add(datasetVector.ChildDataset, true);
                            }
                            map.Refresh();//刷新地图窗口
                        }
                        else
                        {
                            //判断是否已经添加过该数据集
                            bool addNew = true;
                            string Name = datasetVector.Name + "@" + datasetVector.Datasource.Alias;
                            foreach (Layer layer in layers) { if (layer.Name == Name) { addNew = false; } }
                            if (addNew)
                            {
                               layers.Add(datasetVector, true);
                                if (datasetVector.ChildDataset != null) //判断是否有子数据集
                                { 
                                    layers.Add(datasetVector.ChildDataset, true); 
                                }
                                map.Refresh();//刷新地图窗口
                            }
                            else
                            {
                                //先移除
                                layers.Remove(Name);
                                if (datasetVector.ChildDataset != null) 
                                { 
                                    layers.Remove(datasetVector.ChildDataset.Name + "@" + datasetVector.Datasource.Alias); 
                                }
                                //再添加
                                layers.Add(datasetVector, true);
                                if (datasetVector.ChildDataset != null) //判断是否有子数据集
                                { 
                                    layers.Add(datasetVector.ChildDataset, true); 
                                }
                                map.Refresh();//刷新地图窗口
                            }
                        }
                        map.ViewEntire();//全幅显示
                    }
                }
                else
                {
                    MessageBox.Show("当前图层不可用！", "提示：");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 打开属性表
        /// </summary>
        /// <param name="dataGridView">传入属性表</param>
        /// <param name="selectNode">用户选中的工作空间树节点</param>
        public void OpenDataTable(DataGridView dataGridView, WorkspaceTreeNodeBase selectNode)
        {
            try
            {
                if(dataGridView.Columns.Count > 0) //清除属性表已有数据
                { 
                    dataGridView.Rows.Clear(); 
                    dataGridView.Columns.Clear(); 
                }
                if (selectNode.NodeType == WorkspaceTreeNodeDataType.DatasetVector)//判断数据类型
                {
                    DatasetVector datasetVector = selectNode.GetData() as DatasetVector;//获取数据
                    Recordset recordSet = datasetVector.GetRecordset(false, CursorType.Static);//获取记录集
                    //填充列字段
                    foreach (FieldInfo fieldInfo in recordSet.GetFieldInfos())
                    {
                        dataGridView.Columns.Add(fieldInfo.Name,fieldInfo.Caption);
                    }
                    //填充行数据
                    if (recordSet.MoveFirst())//确保初始在第一条记录
                    {
                        for (int i = 0; i < recordSet.RecordCount; i++)//遍历每一条记录
                        {
                            dataGridView.Rows.Add();
                            for (int j = 0; j < recordSet.FieldCount; j++)//填充每行单元格
                            {
                                //dataGridView.Rows[i].Cells[j].ValueType = recordSet.GetFieldValue(j).GetType();
                                dataGridView.Rows[i].Cells[j].Value = recordSet.GetFieldValue(j);
                            }
                            recordSet.MoveNext();//移动到下一行
                        }
                    }
                    recordSet.Dispose();//释放记录集
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 打开属性表
        /// </summary>
        /// <param name="dataGridView">传入属性表</param>
        /// <param name="recordSet">用户选择的数据集的记录集</param>
        public void OpenDataTable(DataGridView dataGridView, Recordset recordSet)
        {
            try
            {
                //填充列字段
                foreach (FieldInfo fieldInfo in recordSet.GetFieldInfos())
                {
                    dataGridView.Columns.Add(fieldInfo.Name, fieldInfo.Caption);
                }
                //填充行数据
                if (recordSet.MoveFirst())//确保初始在第一条记录
                {
                    for (int i = 0; i < recordSet.RecordCount; i++)//遍历每一条记录
                    {
                        dataGridView.Rows.Add();
                        for (int j = 0; j < recordSet.FieldCount; j++)//填充每行单元格
                        {
                            dataGridView.Rows[i].Cells[j].Value = recordSet.GetFieldValue(j);
                        }
                        recordSet.MoveNext();//移动到下一行
                    }
                }
                recordSet.Dispose();//释放记录集
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 关闭属性表（未使用）
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="selectNode"></param>
        public void CloseDatatable(DataGridView dataGridView, WorkspaceTreeNodeBase selectNode)
        {
            try
            {
                
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 打开字段信息表(未使用)
        /// </summary>
        public void OpenDatasetInfos(DataGridView dataGridView, WorkspaceTreeNodeBase selectNode)
        {
            try
            {

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改数据集字段信息
        /// </summary>
        /// <param name="index">字段序号</param>
        /// <param name="attributeName">字段属性名</param>
        /// <param name="value">修改值</param>
        /// <param name="datasetVector">数据集</param>
        public void ReviseDatasetInfos(int index, string attributeName, object value, DatasetVector datasetVector)
        {
            try
            {
                //获取数据集字段信息
                datasetVector.IsReadOnly = false;
                FieldInfos datasetVectorInfos = datasetVector.FieldInfos;
                //获取要修改的字段
                switch (attributeName)
                {
                    case "Caption":
                        datasetVectorInfos[index].Caption = value.ToString();
                        break;
                    case "Type":
                        datasetVectorInfos[index].Type = GetFieldType(value.ToString());
                        break;
                    case "MaxLength":
                        datasetVectorInfos[index].MaxLength = int.Parse(value.ToString());
                        break;
                    case "IsRequired":
                        if (value.ToString() == "True")
                        {
                            datasetVectorInfos[index].IsRequired = true;
                        }
                        else
                        {
                            datasetVectorInfos[index].IsRequired = false;
                        }
                        break;
                    case "DefaultValue":
                        datasetVectorInfos[index].DefaultValue = value.ToString();
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取FieldType枚举值
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        private FieldType GetFieldType(string typeName)
        {
            try
            {
                switch (typeName)
                {
                    case "Boolean":
                        return FieldType.Boolean;
                    case "Byte":
                        return FieldType.Byte;
                    case "Int16":
                        return FieldType.Int16;
                    case "Int32":
                        return FieldType.Int32;
                    case "Single":
                        return FieldType.Single;
                    case "Double":
                        return FieldType.Double;
                    case "Text":
                        return FieldType.Text;
                    case "LongBinary":
                        return FieldType.LongBinary;
                    case "Int64":
                        return FieldType.Int64;
                    case "Char":
                        return FieldType.Char;
                    case "DateTime":
                        return FieldType.DateTime;
                    case "WText":
                        return FieldType.WText;
                    case "JsonB":
                        return FieldType.JsonB;
                    default:
                        return FieldType.WText;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改数据集属性信息
        /// </summary>
        /// <param name="recordIndex">记录序号</param>
        /// <param name="fieldIndex">字段序号</param>
        /// <param name="value">修改值</param>
        /// <param name="datasetVector">数据集</param>
        public void ReviseDatasetRecord(int recordIndex, int fieldIndex, object value, DatasetVector datasetVector)
        {
            try
            {
                //获取记录集
                Recordset recordset = datasetVector.GetRecordset(false, CursorType.Dynamic);
                //定位记录
                recordset.MoveTo(recordIndex);
                //开启编辑
                recordset.Edit();
                recordset.SetFieldValue(fieldIndex, value);
                //提交更新
                recordset.Update();
                //释放记录集
                recordset.Dispose();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }//class-end
}//namespace-end
